package com.uyayo.portal.freemarker;

import com.uyayo.cms.entity.CmsLink;
import com.uyayo.cms.model.CmsLinkCondition;
import com.uyayo.cms.service.CmsLinkService;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * CMS链接全局模板类
 * Created by hfj
 * on 2021/4/1.
 */
public class CmsLinkListDirective implements TemplateDirectiveModel {

    @Autowired
    private CmsLinkService cmsLinkService;

    @Override
    public void execute(Environment environment, Map params, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {

        Integer page = Integer.valueOf(getParam(params,"page","0"));
        Integer pageSize = Integer.valueOf(getParam(params,"pageSize","1"));

        CmsLinkCondition cmsLinkCondition = new CmsLinkCondition();
        cmsLinkCondition.setStatus((short) 1);
        PageBean<CmsLink> pageBean = cmsLinkService.selectLinkByPaging(page,pageSize,null,null,cmsLinkCondition);
        environment.setVariable("cmsLinkList", getBeansWrapper().wrap(pageBean.getList()));
        templateDirectiveBody.render(environment.getOut());
    }

    public static BeansWrapper getBeansWrapper(){
        return new BeansWrapperBuilder(Configuration.VERSION_2_3_25).build();
    }


    /**
     * 获取参数值
     * @param params
     * @param key
     * @return
     * @throws TemplateException
     */
    private String getRequiredParam(Map params,String key) throws TemplateException {
        Object value = params.get(key);
        if(value == null || StringUtils.isEmpty(value.toString())) {
            throw new TemplateModelException("not found required parameter:"+key+" for directive");
        }
        return value.toString();
    }

    /**
     * 获取参数值
     * @param params
     * @param key
     * @param defaultValue
     * @return
     * @throws TemplateException
     */
    private String getParam(Map params,String key,String defaultValue){
        Object value = params.get(key);
        return value == null ? defaultValue : value.toString();
    }
}
